import logging
import argparse
from backtest.engine import BacktestEngine
from backtest.strategies import AllWeatherStrategy

def setup_logging(log_level=logging.INFO, log_file='backtest.log'):
    """
    配置日志系统

    参数:
        log_level: 日志级别 (默认INFO)
        log_file: 日志文件路径 (默认backtest.log)
    """
    # 创建格式化器
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )

    # 创建文件处理器
    file_handler = logging.FileHandler(log_file)
    file_handler.setLevel(log_level)
    file_handler.setFormatter(formatter)

    # 创建控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setLevel(log_level)
    console_handler.setFormatter(formatter)

    # 获取根日志记录器
    logger = logging.getLogger()
    logger.setLevel(log_level)

    # 添加处理器
    logger.addHandler(file_handler)
    logger.addHandler(console_handler)

    return logger

def parse_arguments():
    """
    解析命令行参数
    """
    parser = argparse.ArgumentParser(description='全天候投资策略回测系统')

    parser.add_argument(
        '--config',
        default='config.yaml',
        help='配置文件路径 (默认: config.yaml)'
    )

    parser.add_argument(
        '--log-level',
        default='DEBUG',
        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
        help='日志级别 (默认: INFO)'
    )

    parser.add_argument(
        '--log-file',
        default='backtest.log',
        help='日志文件路径 (默认: backtest.log)'
    )

    parser.add_argument(
        '--plot',
        action='store_true',
        help='是否绘制回测结果图表'
    )

    return parser.parse_args()

def print_results_summary(summary):
    """
    打印回测结果摘要

    参数:
        summary: 回测结果摘要字典
    """
    if not summary:
        print("无有效的回测结果摘要")
        return

    print("\n================ 回测结果摘要 ================")
    print(f"最终资产价值: {summary['final_value']:.2f}")

    # 打印收益分析
    returns = summary.get('returns', {})
    if 'rtot' in returns:
        print(f"\n总收益率: {returns['rtot']*100:.2f}%")
    if 'rnorm100' in returns:
        print(f"年化收益率: {returns['rnorm100']:.2f}%")
    if 'rtot' in returns and 'drawdown' in summary:
        # 计算Calmar比率
        max_drawdown = summary['drawdown'].get('max', {}).get('drawdown', 0)
        if max_drawdown > 0:
            calmar_ratio = returns['rtot'] / max_drawdown
            print(f"Calmar比率: {calmar_ratio:.2f}")

    # 打印风险分析
    sharpe = summary.get('sharpe_ratio', {})
    if 'sharperatio' in sharpe:
        print(f"\n夏普比率: {sharpe['sharperatio']:.3f}")

    drawdown = summary.get('drawdown', {})
    if 'max' in drawdown:
        max_dd = drawdown['max']
        print(f"最大回撤: {max_dd['drawdown']*100:.2f}%")
        print(f"最大回撤周期: {max_dd['len']}个交易日")

    # 打印交易分析
    trades = summary.get('trades', {})
    if 'total' in trades:
        print(f"\n交易总数: {trades['total']}")
        print(f"盈利交易: {trades.get('won', 0)} ({(trades.get('won', 0)/trades['total'])*100:.1f}%)")
        print(f"亏损交易: {trades.get('lost', 0)} ({(trades.get('lost', 0)/trades['total'])*100:.1f}%)")
        print(f"盈利/亏损比例: {trades.get('pnl', {}).get('gross', {}).get('won', 0)/abs(trades.get('pnl', {}).get('gross', {}).get('lost', 1)):.2f}:1")
        print(f"平均每笔交易利润: {trades.get('pnl', {}).get('net', {}).get('average', 0):.2f}")
    print("==============================================")

def main():
    """
    主函数
    """
    # 解析命令行参数
    args = parse_arguments()

    # 设置日志
    logger = setup_logging(log_level=getattr(logging, args.log_level), log_file=args.log_file)
    logger.info("启动全天候投资策略回测系统")

    try:
        # 创建回测引擎
        logger.info(f"创建回测引擎，使用配置文件: {args.config}")
        engine = BacktestEngine(config_file=args.config)

        # 运行回测
        logger.info("开始回测...")
        results = engine.run(AllWeatherStrategy)

        if results:
            result = results[0]
            logger.info("回测完成，处理结果...")

            # 获取结果摘要
            summary = engine.get_results_summary(result)

            # 打印结果摘要
            print_results_summary(summary)

            # 如果指定了--plot选项，则绘制结果
            if args.plot:
                logger.info("绘制回测结果图表...")
                engine.plot_results()

        logger.info("程序执行完成")
    except Exception as e:
        logger.critical(f"程序发生严重错误: {str(e)}", exc_info=True)
        print(f"程序执行失败，请查看日志文件 {args.log_file} 获取详细信息")

if __name__ == "__main__":
    main()